<template>
  <div class="article-page">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>面经后台</el-breadcrumb-item>
      <el-breadcrumb-item>面经管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card shadow="never" border="false">
      <!-- 头部 -->
      <template #header>
        <div class="header">
          <span>共 {{total}} 条记录</span>
          <el-button
            icon="el-icon-plus"
            size="small"
            type="primary"
            round @click="showDrawer('add')">
            添加面经
          </el-button>
        </div>
      </template>
      <!-- 表格组件 -->
          <el-table
            :data="rows" style="width: 100%" border>
            <!-- prop是渲染的字段名，label是列的标题名 -->
          <el-table-column prop="stem" label="标题" width="380"></el-table-column>
          <el-table-column prop="creator" label="作者"></el-table-column>
          <el-table-column prop="likeCount" label="点赞"></el-table-column>
          <el-table-column prop="views" label="浏览数"></el-table-column>
          <el-table-column prop="createdAt" label="更新时间" width="200"></el-table-column>
          <el-table-column label="操作">
            <!-- 组件内的插槽上绑定一些数据 row当前这一行的数据 -->
            <template #default="{ row }">
              <!-- {row.id} 能拿到每一项的id，通过id进行增删改查 携带id发送请求等.-->
            <div class="actions">
              <i class="el-icon-view" @click="showDrawer('preview',(row.id))"></i>
              <i class="el-icon-edit-outline" @click="showDrawer('edit',(row.id))"></i>
              <i class="el-icon-delete" @click="del(row.id)"></i>
            </div>
            </template>
          </el-table-column>
    </el-table>
    <!-- 分页组件 -->
      <el-pagination
      background
      :current-page="current"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      >
    </el-pagination>
    <!-- 抽屉组件 -->
    <el-drawer
      :title="title"
      size="50%"
      :visible.sync="isshow"
      :before-close="handleClose">
      <!-- 预览功能里的盒子 -->
      <div v-if="type==='preview'" class="article-preview">
        <h5>{{form.stem}}</h5>
        <div v-html="form.content"></div>
      </div>
      <!-- 表单 -->
      <el-form v-else :model="form" ref="fref" :rules="rules" label-width="80px">
      <!-- 标题 -->
        <el-form-item label="标题" prop="stem">
          <el-input v-model="form.stem" placeholder="请输入标题"></el-input>
        </el-form-item>
      <!-- 内容 -->
        <el-form-item label="内容" prop="content">
        <quill-editor v-model="form.content" @change="handleBlur"></quill-editor>
        </el-form-item>
        <!-- 按钮 -->
         <el-form-item>
        <el-button type="primary" @click="handleSubmit">确认</el-button>
        <el-button @click="handleClose">取消</el-button>
     </el-form-item>
      </el-form>
    </el-drawer>
    </el-card>
  </div>
</template>

<script>
// 富文本编辑器
// require styles
// 引入样式
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
// 按需引入
import { quillEditor } from 'vue-quill-editor'
import { reqGetlist, reqAddArticle, reqDelArticle, reqGetArticleInfo, reqUpdateArticle } from '@/api/article'
export default {
  name: 'article-page',
  components: {
    quillEditor
  },
  data () {
    return {
      total: 0, // 总数
      rows: [], // 列表总数
      current: 1, // 第几页
      pageSize: 10, // ？条每页
      isshow: false, // 抽屉
      type: '', // 标识
      form: { // 表单数据
        stem: '', // 标题
        content: ''// 内容
      },
      rules: { // 校验规则
        stem: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
        content: [{ required: true, message: '内容不能为空', trigger: 'blur' }]
      }
    }
  },
  created () {
    // 钩子函数created触发立即执行getArticleList方法获取数据
    this.getArticleList()
  },
  computed: {
    title () {
      if (this.type === 'add') return '添加面经'
      if (this.type === 'preview') return '预览面经'
      if (this.type === 'edit') return '编辑面经'
      return '默认标题'
    }
  },
  methods: {
    // 获取面经列表
    async getArticleList () {
      const { data: { total, rows } } = await reqGetlist(this.current, this.pageSize)
      this.total = total
      this.rows = rows
    },
    // 每页条数发生变化触发的处理函数
    handleSizeChange (newsize) {
      // 将最新的每页条数设置给pageSize 并重新渲染页面
      this.pageSize = newsize
      this.getArticleList()
    },
    // 页码发生变化触发的处理函数
    handleCurrentChange (newcurrent) {
      // 将最新的页码赋值给current，并重新渲染页面
      this.current = newcurrent
      this.getArticleList()
    },
    // 展示抽屉
    async showDrawer (str, id) {
      // console.log(str)// 基于str 来处理添加/预览/编辑
      this.type = str
      this.isshow = true
      if (id) {
      // 携带id来查询文章详情
        const { data } = await reqGetArticleInfo(id)
        // console.log(data)// data是获取到的单个文章信息
        // 让form里的标题和内容等于data
        this.form = data
      }
    },
    // 关闭抽屉
    handleClose () {
      this.isshow = false
      // 重置表单 重置的是表单关联的字段
      if (this.type !== 'preview') {
        this.$refs.fref.resetFields()
      }
      this.form = {
        stem: '',
        content: ''
      }// 解决先编辑在新增的bug
    },
    // 内容校验
    handleBlur () {
      // 富文本失去焦点后,调用form组件的validateField('校验的字段')
      this.$refs.fref.validateField('content')
    },
    // 表单提交
    async handleSubmit () {
      try {
        // 判断如果表单里面存在id那就是编辑,如果不存在id则是新增
        if (this.form.id) {
          await reqUpdateArticle({ id: this.form.id, stem: this.form.stem, content: this.form.content })
          // console.log(res)
          // 提示用户
          this.$message.success('修改成功')
        } else {
          // 1,预校验
          await this.$refs.fref.validate()
          // 2,准备接口发送请求,携带参数
          await reqAddArticle(this.form)
          // 3,提示用户,新增成功
          this.$message.success('新增成功')
        }
        // 关闭抽屉
        this.handleClose()
        // 手动将页码重置为1
        this.current = 1
        // 4,重新获取列表数据
        this.getArticleList()
      } catch {}
    },
    // 表单删除
    del (id) {
      // 弹出消息提示框
      this.$confirm('此操作将永久删除该文章,是否继续?', '温馨提示', {
        type: 'warning'
      }).then(async () => {
        // 发送请求
        await reqDelArticle(id)
        // 提示
        this.$message.success('删除成功')
        // bug处理,如果表格只有一个数据,删除完后该让current页面--
        if (this.rows.length === 1 && this.current > 1) {
          this.current--
        }
        // 重新渲染
        this.getArticleList()
      }).catch(() => {
        this.$message('已取消删除')
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.el-card {
  margin-top: 25px;
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-right: 16px;
  }
  .actions {
    font-size: 18px;
    display: flex;
    justify-content: space-around;
    color: #666;
    > i:hover {
      color: rgba(114, 124, 245, 1);
      cursor: pointer;
    }
  }
}
.el-pagination {
  margin-top: 20px;
  text-align: center;
}
.el-breadcrumb {
  margin-top: 10px;
}
.el-form {
  padding-right: 40px;
}
.quill-editor {
  ::v-deep .ql-editor {
    height: 300px;
  }
}
.el-rate {
  padding: 10px 0;
}
.article-preview {
  padding: 0 40px 40px 40px;
  > h5 {
    font-size: 20px;
    color: #666;
    border-bottom: 1px dashed #ccc;
    padding-bottom: 30px;
    margin: 0 0 20px 0;
  }
}
</style>
